package resources

import (
	"context"
	"errors"
	"fmt"
	"gitee.com/Luna-CY/hui-hui/internal/util/archive"
	"os"
	"path/filepath"
)

// Compress 压缩
func (cls *Resources) Compress(paths []string, t ArchiveType) error {
	var path, err = cls.normal(paths)
	if nil != err {
		return err
	}

	path = filepath.Join(cls.path, path)
	stat, err := os.Stat(path)
	if nil != err && !os.IsNotExist(err) {
		return err
	}

	if os.IsNotExist(err) {
		return errors.New("文件不存在")
	}

	cls.sm.Lock()
	cls.state[path] = EntryStateCompressing
	cls.sm.Unlock()

	defer func() {
		cls.sm.Lock()
		defer cls.sm.Unlock()

		delete(cls.state, path)
	}()

	switch t {
	case ArchiveTypeGzip:
		if stat.IsDir() {
			return archive.CompressGzipFileFromPath(context.Background(), path, fmt.Sprintf("%s.tar.gz", path))
		}

		return archive.CompressGzipFileFromPath(context.Background(), path, fmt.Sprintf("%s.gz", path))
	case ArchiveTypeZip:
		return archive.CompressZipFile(context.Background(), path, fmt.Sprintf("%s.zip", path))
	case ArchiveTypeXzip:
		if stat.IsDir() {
			return archive.CompressXzFile(context.Background(), path, fmt.Sprintf("%s.tar.xz", path))
		}

		return archive.CompressXzFile(context.Background(), path, fmt.Sprintf("%s.xz", path))
	}

	return errors.New("暂未支持的压缩类型")
}
